package com.example.czxyindex.web;

import com.example.czxyindex.web.remote.IProductAction;
import com.yc.czxy.bean.Category;
import com.yc.czxy.bean.Categorysecond;
import com.yc.czxy.bean.Product;
import com.yc.czxy.bean.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @program: chengzixy
 * @description:商品操作
 * @author: 刘志成
 * @create: 2021-08-30 12:54
 */
@Controller
public class ProductAction {


    @Resource
    IProductAction iProductAction;

    /**
     * 查询所有主类别
     * @return
     */
    @GetMapping("selectAllCategory")
    @ResponseBody
    public List<Category>  selectAllCategory() {
        return iProductAction.selectAllCategory();
    }
    @GetMapping("selectCategorySecondBycid")
    @ResponseBody
    public List<Categorysecond> selectCategorySecondBycid(Integer cid) {
        return iProductAction.selectCategorySecondBycid(cid);
    }

    /**
     * 添加商品
     *
     * @param product
     * @return
     */
    @PostMapping("addProduct")
    @ResponseBody
    public Result<Product> addProduct(Product product) {
        return iProductAction.addProduct(product);
    }

    /**
     * 删除商品
     * @param product
     * @return
     */
    @PostMapping("deleteProductBypid")
    @ResponseBody
    public Result<Product> deleteProductBypid(Product product) {
        return iProductAction.deleteProductBypid(product);
    }



    /**
     * 文件上传
     */
    @PostMapping("upload")
    @ResponseBody
    public Result upload(MultipartFile head){
        //获取到需要传入的路径
        String diskpath = System.getProperty("user.dir")+"/czxy-index/src/main/resources/static/img/product"+"/"+head.getOriginalFilename();
        //设置前端需要判断src的路径
        String webpath = "img/product/"+head.getOriginalFilename();
        try {
            head.transferTo(new File(diskpath));
            return new Result(1,"上传成功",webpath);
        }catch (IOException e){
            e.printStackTrace();
            return new Result(0,"上传失败",e.getMessage());
        }
    }

    /**
     * 根据用户id查询所拥有的商品
     * @param uid
     * @return
     */
    @GetMapping("selectProductByUid")
    @ResponseBody
    public List<Product> selectProductByUid(Integer uid){
        List<Product> product = iProductAction.selectProductByUid(uid);
        return product;
    }




}
